package com.uzai.console.service.groupsendjob.impl;
import com.google.common.collect.Lists;
import com.uzai.console.dto.groupsendjob.GroupSendJobUserQueryParaDto;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.entity.User;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.groupsendjob.GroupSendJobIdFeignDto;
import com.uzai.console.dto.groupsendjob.*;
import com.uzai.console.dto.wechatprivate.wxcontacts.NewBatchSendMessageTaskDto;
import com.uzai.console.dto.wechatprivate.wxcontacts.WxContactsQuery;
import com.uzai.console.dto.wechatwork.wxworkcontacts.WxworkContactsQuery;
import com.uzai.console.dto.wechatwork.wxworkcontacts.WxworkNewBatchSendMessageTaskDto;
import com.uzai.console.entity.*;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.groupsendjob.GroupSendJobService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.wechatprivate.WxContactsGroupSendMsgService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.service.wechatprivate.WxContactsSyncService;
import com.uzai.console.service.wechatwork.WxworkContactsGroupSendMsgService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.vo.groupsendjob.GroupSendCountVo;
import com.uzai.console.vo.groupsendjob.GroupSendJobInfoVo;
import com.uzai.console.vo.groupsendjob.GroupSendJobSendErrInfoVo;
import com.uzai.console.vo.user.SysTagVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 群发任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class GroupSendJobServiceImpl implements GroupSendJobService {

    Logger logger = LoggerFactory.getLogger(GroupSendJobServiceImpl.class);

    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private WxContactsSyncService wxContactsSyncService;
    @Autowired
    private WxContactsService wxContactsService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private WxContactsGroupSendMsgService wxContactsGroupSendMsgService;
    @Autowired
    private WxworkContactsGroupSendMsgService wxworkContactsGroupSendMsgService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private WxworkContactsService wxworkContactsService;

    /**
     * 查询群发任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobQuery
     * @return null
     */
    public Page<GroupSendJobInfoVo> findGroupSendJobList(GroupSendJobQuery groupSendJobQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<GroupSendJobInfoVo> groupSendJobInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<GroupSendJob> page = new Page<>();
        groupSendJobQuery.convert(page);
        List<GroupSendJob> groupSendJobList = groupSendJobMapper.findByList(page, groupSendJobQuery);
        if(groupSendJobList != null){
            for (GroupSendJob groupSendJob : groupSendJobList){
                GroupSendJobInfoVo groupSendJobInfoVo = new GroupSendJobInfoVo();
                BeanUtils.copyProperties(groupSendJob, groupSendJobInfoVo);
                //查询已发送数
                int findFinishCount = 0;
                //findFinishCount = Tools.getInteger(groupSendJobMapper.findFinishCountByParentId(groupSendJob.getId(), groupSendJob.getMerId()));
                //groupSendJobInfoVo.setFinishCount(findFinishCount);
                //查询总数
                int totalCount = 0;
                // totalCount = Tools.getInteger(groupSendJobMapper.findTotalCountByParentId(groupSendJob.getId(), groupSendJob.getMerId()));
                //groupSendJobInfoVo.setTotalCount(totalCount);
                //发送失败数对象
                GroupSendJobSendErrInfoVo sendErrInfoVo = new GroupSendJobSendErrInfoVo();
                //查询该主任务的子任务信息
                GroupSendJobQuery groupSendJobQuery_parentId = new GroupSendJobQuery();
                groupSendJobQuery_parentId.setMerId(groupSendJob.getMerId());
                groupSendJobQuery_parentId.setParentId(groupSendJob.getId());
                List<GroupSendJob> groupSendJobList_sun = groupSendJobMapper.findByList(groupSendJobQuery_parentId);
                if(groupSendJobList_sun != null){
                    for (GroupSendJob sendJob_sun : groupSendJobList_sun) {
                        //查询总数
                        totalCount = totalCount + Tools.getInteger(sendJob_sun.getTotalCount());
                        //查询已发送数
                        findFinishCount = findFinishCount + Tools.getInteger(sendJob_sun.getFinishCount());
                        //查询发送失败数
                        if(StringUtils.isNotBlank(sendJob_sun.getSendErrInfo())){
                            try{
                                GroupSendJobSendErrInfoVo groupSendJobSendErrInfoVo_sun = JSONObject.parseObject(sendJob_sun.getSendErrInfo(), GroupSendJobSendErrInfoVo.class);
                                if(groupSendJobSendErrInfoVo_sun != null){
                                    sendErrInfoVo.add(groupSendJobSendErrInfoVo_sun);
                                }
                            }catch (Exception e){}
                        }
                    }
                }
                groupSendJobInfoVo.setTotalCount(totalCount);
                groupSendJobInfoVo.setFinishCount(findFinishCount);
                groupSendJobInfoVo.setSendErrInfo(sendErrInfoVo);
                groupSendJobInfoVo.setSendErrTotal(sendErrInfoVo.getTotal());

                //如果完成发送总数大于预计发送总数，则预计发送总数显示为完成发送总数
                if(findFinishCount >= totalCount){
                    groupSendJobInfoVo.setTotalCount(findFinishCount);
                }

                //修改状态-已完成,必须主任务创建30分钟（1800秒）
                if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.FINISH.getValue().intValue()){
                    if(now - groupSendJob.getCreateTime() > 1800){
                        if(findFinishCount >= totalCount - sendErrInfoVo.getTotal()){
                            groupSendJobInfoVo.setStatus(3);
                            //修改主任务
                            groupSendJob.setStatus(3);
                            groupSendJob.setUpdateTime(now);
                            groupSendJobMapper.updateById(groupSendJob);
                            //修改子任务
                            groupSendJobMapper.updateByParentId(groupSendJob);
                        }
                    }
                }

                //查询群发类型名称
                if(StringUtils.isNotBlank(groupSendJob.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(groupSendJob.getDeviceType());
                    if(deviceTypeEnum != null){
                        groupSendJobInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                //标签
                if(StringUtils.isNotBlank(groupSendJob.getUserLab())){
                    groupSendJobInfoVo.setUserLabList(JSONObject.parseArray(groupSendJob.getUserLab(), String.class));
                }

                //群发来源
                if(groupSendJobInfoVo.getSource() != null){
                    GroupSendJobSourceEnum groupSendJobSourceEnum = GroupSendJobSourceEnum.getById(groupSendJobInfoVo.getSource());
                    if(groupSendJobSourceEnum != null){
                        groupSendJobInfoVo.setSourceName(groupSendJobSourceEnum.getDesc());
                    }
                }

                //屏蔽关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnore())){
                    groupSendJobInfoVo.setIgnoreList(JSONObject.parseArray(groupSendJob.getIgnore(), String.class));
                }

                //屏蔽昵称关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnoreName())){
                    groupSendJobInfoVo.setIgnoreNameList(JSONObject.parseArray(groupSendJob.getIgnoreName(), String.class));
                }

                //屏蔽备注关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnoreRemark())){
                    groupSendJobInfoVo.setIgnoreRemarkList(JSONObject.parseArray(groupSendJob.getIgnoreRemark(), String.class));
                }

                if(StringUtils.isNotBlank(groupSendJob.getUserQueryPara())){
                    try{
                        GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = JSONObject.parseObject(groupSendJob.getUserQueryPara(), GroupSendJobUserQueryParaDto.class);
                        groupSendJobInfoVo.setUserQueryParaDto(groupSendJobUserQueryParaDto);
                    }catch (Exception e){}
                }

                groupSendJobInfoVoList.add(groupSendJobInfoVo);

            }
        }
        //返回到页面分页对象
        Page<GroupSendJobInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(groupSendJobInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询群发任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobIdDto
     * @return null
     */
    public GroupSendJobInfoVo findGroupSendJobInfo(GroupSendJobIdDto groupSendJobIdDto){
        //返回到页面的VO对象
        GroupSendJobInfoVo groupSendJobInfoVo = new GroupSendJobInfoVo();

        if(groupSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobIdDto.getId(), groupSendJobIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(groupSendJob, groupSendJobInfoVo);

        //查询已发送数
        int findFinishCount = 0;
        //findFinishCount = Tools.getInteger(groupSendJobMapper.findFinishCountByParentId(groupSendJob.getId(), groupSendJob.getMerId()));
        //groupSendJobInfoVo.setFinishCount(findFinishCount);
        //查询总数
        int totalCount = 0;
        // totalCount = Tools.getInteger(groupSendJobMapper.findTotalCountByParentId(groupSendJob.getId(), groupSendJob.getMerId()));
        //groupSendJobInfoVo.setTotalCount(totalCount);
        //发送失败数对象
        GroupSendJobSendErrInfoVo sendErrInfoVo = new GroupSendJobSendErrInfoVo();
        //查询该主任务的子任务信息
        GroupSendJobQuery groupSendJobQuery_parentId = new GroupSendJobQuery();
        groupSendJobQuery_parentId.setMerId(groupSendJob.getMerId());
        groupSendJobQuery_parentId.setParentId(groupSendJob.getId());
        List<GroupSendJob> groupSendJobList_sun = groupSendJobMapper.findByList(groupSendJobQuery_parentId);
        if(groupSendJobList_sun != null){
            for (GroupSendJob sendJob_sun : groupSendJobList_sun) {
                //查询总数
                totalCount = totalCount + Tools.getInteger(sendJob_sun.getTotalCount());
                //查询已发送数
                findFinishCount = findFinishCount + Tools.getInteger(sendJob_sun.getFinishCount());
                //查询发送失败数
                if(StringUtils.isNotBlank(sendJob_sun.getSendErrInfo())){
                    try{
                        GroupSendJobSendErrInfoVo groupSendJobSendErrInfoVo_sun = JSONObject.parseObject(sendJob_sun.getSendErrInfo(), GroupSendJobSendErrInfoVo.class);
                        if(groupSendJobSendErrInfoVo_sun != null){
                            sendErrInfoVo.add(groupSendJobSendErrInfoVo_sun);
                        }
                    }catch (Exception e){}
                }
            }
        }
        groupSendJobInfoVo.setTotalCount(totalCount);
        groupSendJobInfoVo.setFinishCount(findFinishCount);
        groupSendJobInfoVo.setSendErrInfo(sendErrInfoVo);
        groupSendJobInfoVo.setSendErrTotal(sendErrInfoVo.getTotal());

        //查询群发类型名称
        if(StringUtils.isNotBlank(groupSendJob.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(groupSendJob.getDeviceType());
            if(deviceTypeEnum != null){
                groupSendJobInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        //自定义标签
        if(StringUtils.isNotBlank(groupSendJob.getUserLab())){
            groupSendJobInfoVo.setUserLabList(JSONObject.parseArray(groupSendJob.getUserLab(), String.class));
        }

        //会员标签
        if(StringUtils.isNotBlank(groupSendJob.getUserTags())){
            groupSendJobInfoVo.setUserTagsList(JSONObject.parseArray(groupSendJob.getUserTags(), SysTagVo.class));
        }

        //群发来源
        if(groupSendJobInfoVo.getSource() != null){
            GroupSendJobSourceEnum groupSendJobSourceEnum = GroupSendJobSourceEnum.getById(groupSendJobInfoVo.getSource());
            if(groupSendJobSourceEnum != null){
                groupSendJobInfoVo.setSourceName(groupSendJobSourceEnum.getDesc());
            }
        }

        //屏蔽关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnore())){
            groupSendJobInfoVo.setIgnoreList(JSONObject.parseArray(groupSendJob.getIgnore(), String.class));
        }

        //屏蔽昵称关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnoreName())){
            groupSendJobInfoVo.setIgnoreNameList(JSONObject.parseArray(groupSendJob.getIgnoreName(), String.class));
        }

        //屏蔽备注关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnoreRemark())){
            groupSendJobInfoVo.setIgnoreRemarkList(JSONObject.parseArray(groupSendJob.getIgnoreRemark(), String.class));
        }

        if(StringUtils.isNotBlank(groupSendJob.getUserQueryPara())){
            try{
                GroupSendJobUserQueryParaDto userQueryParaDto = JSONObject.parseObject(groupSendJob.getUserQueryPara(), GroupSendJobUserQueryParaDto.class);
                groupSendJobInfoVo.setUserQueryParaDto(userQueryParaDto);
            }catch (Exception e){}
        }

        return  groupSendJobInfoVo;
    }

    /**
     * 查询添加群发任务任务总数
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobAddDto
     * @return null
     */
    public GroupSendCountVo findAddGroupSendJobCount(GroupSendJobAddDto groupSendJobAddDto){

        if(groupSendJobAddDto.getDeviceUniqueIdList() == null || groupSendJobAddDto.getDeviceUniqueIdList().size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群发机器人");
        }

        GroupSendCountVo groupSendCountVo = new GroupSendCountVo();
        int totalCount = 0; //默认总数为0
        if(StringUtils.isBlank(groupSendJobAddDto.getDeviceType())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人类型不能为空");
        }

        if(groupSendJobAddDto.getBeginTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入发送时间");
        }

        //个人微信通讯
        if(groupSendJobAddDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){

            //判断通讯录总是是否超过10W
            WxContactsQuery wxContactsQuery = new WxContactsQuery();
            wxContactsQuery.setMerId(groupSendJobAddDto.getMerId());
            wxContactsQuery.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            long total = wxContactsService.searchTotal(wxContactsQuery);
            if(total >= 100000L){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "通讯录总数超过10万，不支持统计总数");
            }

            NewBatchSendMessageTaskDto newBatchSendMessageTaskDto = new NewBatchSendMessageTaskDto();
            BeanUtils.copyProperties(groupSendJobAddDto, newBatchSendMessageTaskDto);
            newBatchSendMessageTaskDto.setMerId(groupSendJobAddDto.getMerId());
            newBatchSendMessageTaskDto.setSubDeviceUniqueIdList(groupSendJobAddDto.getSubDeviceUniqueIdList());
            newBatchSendMessageTaskDto.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            newBatchSendMessageTaskDto.setName(groupSendJobAddDto.getName());
            newBatchSendMessageTaskDto.setIgnoreNameList(groupSendJobAddDto.getNameExcludeList());
            newBatchSendMessageTaskDto.setIgnoreRemarkList(groupSendJobAddDto.getRemarkExcludeList());
            newBatchSendMessageTaskDto.setUserRemark(groupSendJobAddDto.getUserRemark());
            newBatchSendMessageTaskDto.setUserLabList(groupSendJobAddDto.getUserLabList());
            newBatchSendMessageTaskDto.setCleanLab(groupSendJobAddDto.getCleanLab());
            newBatchSendMessageTaskDto.setUserTagsList(groupSendJobAddDto.getUserTagsList());
            newBatchSendMessageTaskDto.setTimeInterval(groupSendJobAddDto.getTimeInterval());
            newBatchSendMessageTaskDto.setNightTime(groupSendJobAddDto.getNightTime());
            newBatchSendMessageTaskDto.setContent(groupSendJobAddDto.getContent());
            newBatchSendMessageTaskDto.setBusyTimeInterval(groupSendJobAddDto.getBusyTimeInterval());
            newBatchSendMessageTaskDto.setBeginTime(groupSendJobAddDto.getBeginTime());
            newBatchSendMessageTaskDto.setGroupSendType(groupSendJobAddDto.getGroupSendType());
            newBatchSendMessageTaskDto.setParaQueryType(groupSendJobAddDto.getParaQueryType());
            //关联会员查询条件
            GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = new GroupSendJobUserQueryParaDto();
            BeanUtils.copyProperties(groupSendJobAddDto, groupSendJobUserQueryParaDto);
            newBatchSendMessageTaskDto.setGroupSendJobUserQueryParaDto(groupSendJobUserQueryParaDto);

            List<Long> deviceUniqueIdList = groupSendJobAddDto.getDeviceUniqueIdList();
            if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
                //循环机器人添加群发子任务
                for(Long deviceUniqueId :  deviceUniqueIdList){
                    if(groupSendJobAddDto.getGroupSendType() == 1) { //群发助手。仅支持手机端机器人
                        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, groupSendJobAddDto.getMerId());
                        if(deviceWechatInfo != null && Tools.getInteger(deviceWechatInfo.getRecvmsgType()).intValue() == 1) {//手机端
                            int sendMsgTotal_real = wxContactsService.findBatchSendMessageTaskSyncCount(newBatchSendMessageTaskDto, deviceUniqueId);
                            totalCount = totalCount + sendMsgTotal_real;
                        }
                    }else{
                        int sendMsgTotal_real = wxContactsService.findBatchSendMessageTaskSyncCount(newBatchSendMessageTaskDto, deviceUniqueId);
                        totalCount = totalCount + sendMsgTotal_real;
                    }
                }
            }
        }else if(groupSendJobAddDto.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){

            //判断通讯录总是是否超过10W
            WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
            wxworkContactsQuery.setMerId(groupSendJobAddDto.getMerId());
            wxworkContactsQuery.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            long total = wxworkContactsService.searchTotal(wxworkContactsQuery);
            if(total >= 100000L){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "通讯录总数超过10万，不支持统计总数");
            }

            WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto = new WxworkNewBatchSendMessageTaskDto();
            BeanUtils.copyProperties(groupSendJobAddDto, wxworkNewBatchSendMessageTaskDto);
            wxworkNewBatchSendMessageTaskDto.setMerId(groupSendJobAddDto.getMerId());
            wxworkNewBatchSendMessageTaskDto.setSubDeviceUniqueIdList(groupSendJobAddDto.getSubDeviceUniqueIdList());
            wxworkNewBatchSendMessageTaskDto.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            wxworkNewBatchSendMessageTaskDto.setName(groupSendJobAddDto.getName());
            wxworkNewBatchSendMessageTaskDto.setIgnoreNameList(groupSendJobAddDto.getNameExcludeList());
            wxworkNewBatchSendMessageTaskDto.setIgnoreRemarkList(groupSendJobAddDto.getRemarkExcludeList());
            wxworkNewBatchSendMessageTaskDto.setUserRemark(groupSendJobAddDto.getUserRemark());
            wxworkNewBatchSendMessageTaskDto.setUserLabList(groupSendJobAddDto.getUserLabList());
            wxworkNewBatchSendMessageTaskDto.setCleanLab(groupSendJobAddDto.getCleanLab());
            wxworkNewBatchSendMessageTaskDto.setUserTagsList(groupSendJobAddDto.getUserTagsList());
            wxworkNewBatchSendMessageTaskDto.setTimeInterval(groupSendJobAddDto.getTimeInterval());
            wxworkNewBatchSendMessageTaskDto.setNightTime(groupSendJobAddDto.getNightTime());
            wxworkNewBatchSendMessageTaskDto.setContent(groupSendJobAddDto.getContent());
            wxworkNewBatchSendMessageTaskDto.setBusyTimeInterval(groupSendJobAddDto.getBusyTimeInterval());
            wxworkNewBatchSendMessageTaskDto.setBeginTime(groupSendJobAddDto.getBeginTime());
            wxworkNewBatchSendMessageTaskDto.setParaQueryType(groupSendJobAddDto.getParaQueryType());
            //关联会员查询条件
            GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = new GroupSendJobUserQueryParaDto();
            BeanUtils.copyProperties(groupSendJobAddDto, groupSendJobUserQueryParaDto);
            wxworkNewBatchSendMessageTaskDto.setGroupSendJobUserQueryParaDto(groupSendJobUserQueryParaDto);

            List<Long> deviceUniqueIdList = groupSendJobAddDto.getDeviceUniqueIdList();
            if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
                //循环机器人添加群发子任务
                for(Long deviceUniqueId :  deviceUniqueIdList){
                    int sendMsgTotal_real = wxworkContactsService.findBatchSendMessageTaskSyncCount(wxworkNewBatchSendMessageTaskDto, deviceUniqueId);
                    totalCount = totalCount + sendMsgTotal_real;
                }
            }
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务目前只支持个人微信和企业微信");
        }

        groupSendCountVo.setTotalCount(totalCount);

        return groupSendCountVo;
    }


    /**
     * 添加群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobAddDto
     * @return null
     */
    public void addGroupSendJob(GroupSendJobAddDto groupSendJobAddDto, String loginName){
        if(StringUtils.isBlank(groupSendJobAddDto.getDeviceType())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人类型不能为空");
        }

        if(groupSendJobAddDto.getDeviceUniqueIdList() == null || groupSendJobAddDto.getDeviceUniqueIdList().size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群发机器人");
        }

        if(groupSendJobAddDto.getTimeIntervalMin() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最小发送间隔时间");
        }

        if(groupSendJobAddDto.getTimeInterval() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最大发送间隔时间");
        }

        if(groupSendJobAddDto.getTimeInterval() < groupSendJobAddDto.getTimeIntervalMin()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大发送间隔时间不能小于最小发送间隔时间");
        }

        //个人微信通讯
        if(groupSendJobAddDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){
            NewBatchSendMessageTaskDto newBatchSendMessageTaskDto = new NewBatchSendMessageTaskDto();
            BeanUtils.copyProperties(groupSendJobAddDto, newBatchSendMessageTaskDto);
            newBatchSendMessageTaskDto.setMerId(groupSendJobAddDto.getMerId());
            newBatchSendMessageTaskDto.setSubDeviceUniqueIdList(groupSendJobAddDto.getSubDeviceUniqueIdList());
            newBatchSendMessageTaskDto.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            newBatchSendMessageTaskDto.setName(groupSendJobAddDto.getName());
            newBatchSendMessageTaskDto.setIgnoreNameList(groupSendJobAddDto.getNameExcludeList());
            newBatchSendMessageTaskDto.setIgnoreRemarkList(groupSendJobAddDto.getRemarkExcludeList());
            newBatchSendMessageTaskDto.setUserRemark(groupSendJobAddDto.getUserRemark());
            newBatchSendMessageTaskDto.setUserLabList(groupSendJobAddDto.getUserLabList());
            newBatchSendMessageTaskDto.setCleanLab(groupSendJobAddDto.getCleanLab());
            newBatchSendMessageTaskDto.setUserTagsList(groupSendJobAddDto.getUserTagsList());
            newBatchSendMessageTaskDto.setTimeIntervalMin(groupSendJobAddDto.getTimeIntervalMin());
            newBatchSendMessageTaskDto.setTimeInterval(groupSendJobAddDto.getTimeInterval());
            newBatchSendMessageTaskDto.setNightTime(groupSendJobAddDto.getNightTime());
            newBatchSendMessageTaskDto.setContent(groupSendJobAddDto.getContent());
            newBatchSendMessageTaskDto.setBusyTimeInterval(groupSendJobAddDto.getBusyTimeInterval());
            newBatchSendMessageTaskDto.setBeginTime(groupSendJobAddDto.getBeginTime());
            newBatchSendMessageTaskDto.setEndTime(groupSendJobAddDto.getEndTime());
            newBatchSendMessageTaskDto.setGroupSendType(groupSendJobAddDto.getGroupSendType());
            newBatchSendMessageTaskDto.setParaQueryType(groupSendJobAddDto.getParaQueryType());
            //关联会员查询条件
            GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = new GroupSendJobUserQueryParaDto();
            BeanUtils.copyProperties(groupSendJobAddDto, groupSendJobUserQueryParaDto);
            newBatchSendMessageTaskDto.setGroupSendJobUserQueryParaDto(groupSendJobUserQueryParaDto);
            wxContactsGroupSendMsgService.newBatchSendMessageTask(newBatchSendMessageTaskDto, loginName);
        }else if(groupSendJobAddDto.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){
            WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto = new WxworkNewBatchSendMessageTaskDto();
            BeanUtils.copyProperties(groupSendJobAddDto, wxworkNewBatchSendMessageTaskDto);
            wxworkNewBatchSendMessageTaskDto.setMerId(groupSendJobAddDto.getMerId());
            wxworkNewBatchSendMessageTaskDto.setSubDeviceUniqueIdList(groupSendJobAddDto.getSubDeviceUniqueIdList());
            wxworkNewBatchSendMessageTaskDto.setDeviceUniqueIdList(groupSendJobAddDto.getDeviceUniqueIdList());
            wxworkNewBatchSendMessageTaskDto.setName(groupSendJobAddDto.getName());
            wxworkNewBatchSendMessageTaskDto.setIgnoreNameList(groupSendJobAddDto.getNameExcludeList());
            wxworkNewBatchSendMessageTaskDto.setIgnoreRemarkList(groupSendJobAddDto.getRemarkExcludeList());
            wxworkNewBatchSendMessageTaskDto.setUserRemark(groupSendJobAddDto.getUserRemark());
            wxworkNewBatchSendMessageTaskDto.setUserLabList(groupSendJobAddDto.getUserLabList());
            wxworkNewBatchSendMessageTaskDto.setCleanLab(groupSendJobAddDto.getCleanLab());
            wxworkNewBatchSendMessageTaskDto.setUserTagsList(groupSendJobAddDto.getUserTagsList());
            wxworkNewBatchSendMessageTaskDto.setTimeIntervalMin(groupSendJobAddDto.getTimeIntervalMin());
            wxworkNewBatchSendMessageTaskDto.setTimeInterval(groupSendJobAddDto.getTimeInterval());
            wxworkNewBatchSendMessageTaskDto.setNightTime(groupSendJobAddDto.getNightTime());
            wxworkNewBatchSendMessageTaskDto.setContent(groupSendJobAddDto.getContent());
            wxworkNewBatchSendMessageTaskDto.setBusyTimeInterval(groupSendJobAddDto.getBusyTimeInterval());
            wxworkNewBatchSendMessageTaskDto.setBeginTime(groupSendJobAddDto.getBeginTime());
            wxworkNewBatchSendMessageTaskDto.setEndTime(groupSendJobAddDto.getEndTime());
            wxworkNewBatchSendMessageTaskDto.setParaQueryType(groupSendJobAddDto.getParaQueryType());
            //关联会员查询条件
            GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = new GroupSendJobUserQueryParaDto();
            BeanUtils.copyProperties(groupSendJobAddDto, groupSendJobUserQueryParaDto);
            wxworkNewBatchSendMessageTaskDto.setGroupSendJobUserQueryParaDto(groupSendJobUserQueryParaDto);
            wxworkContactsGroupSendMsgService.newBatchSendMessageTask(wxworkNewBatchSendMessageTaskDto, loginName);

        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务目前只支持个人微信和企业微信");
        }
    }

    /**
     * 修改群发任务开始时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobUpdateDto
     * @return null
     */
    public void updateGroupSendJob(GroupSendJobUpdateDto groupSendJobUpdateDto){
        if(groupSendJobUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobUpdateDto.getId(), groupSendJobUpdateDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.FINISH.getValue().intValue()
            || groupSendJob.getStatus().intValue() == GroupSendStatusEnum.INVALID.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已经完成或者过期的任务不能修改");
        }

        String content = groupSendJobUpdateDto.getContent();
        if(StringUtils.isBlank(content)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "消息内容不能为空");
        }
        //修改内容
        groupSendJob.setContent(Tools.getStr(content));

        Integer now = DateUtil.getNowTime();

        //未开始任务可以修改开始时间
        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){

            Integer beginTime = groupSendJobUpdateDto.getBeginTime();
            if(beginTime == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能为空");
            }

            if(beginTime-now < 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于当前时间");
            }

            if(beginTime-groupSendJob.getCreateTime() > 7*24*3600){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间必须在创建时间的7天之内");
            }

            groupSendJob.setBeginTime(beginTime);
            groupSendJob.setEndTime(groupSendJobUpdateDto.getEndTime());
            groupSendJob.setSendStartTime(beginTime);
        }

        groupSendJob.setUpdateTime(now);
        //修改主任务
        groupSendJobMapper.updateById(groupSendJob);
        //修改子任务
        groupSendJobMapper.updateByParentId(groupSendJob);
    }

    /**
     * 开始群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobIdDto
     * @return null
     */
    public void startGroupSendJob(GroupSendJobIdDto groupSendJobIdDto){
        if(groupSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobIdDto.getId(), groupSendJobIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue() && groupSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能开启");
        }

        Integer now = DateUtil.getNowTime();
        groupSendJob.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());
        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
            groupSendJob.setBeginTime(now);
            groupSendJob.setSendStartTime(now);
        }else{//暂停中的任务延迟5分钟发送
            groupSendJob.setBeginTime(now+60*5); //延迟5分钟
            groupSendJob.setSendStartTime(now+60*5); //延迟5分钟
        }
        groupSendJob.setUpdateTime(now);
        groupSendJobMapper.updateById(groupSendJob);

        //查询未开始的子任务，修改状态为开始
        GroupSendJobQuery groupSendJobQuery = new GroupSendJobQuery();
        groupSendJobQuery.setMerId(groupSendJobIdDto.getMerId());
        groupSendJobQuery.setParentId(groupSendJob.getId());
        List<GroupSendJob> groupSendJobQueryList =  groupSendJobMapper.findByList(groupSendJobQuery);
        if(groupSendJobQueryList != null){
            for (GroupSendJob groupSendJobSon : groupSendJobQueryList){
                //未开始或者暂停的子任务-将状态修改成进行中
                if(groupSendJobSon.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()
                        || groupSendJobSon.getStatus().intValue() == GroupSendStatusEnum.PAUSE.getValue().intValue()
                ){

                    if(groupSendJobSon.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
                        groupSendJobSon.setBeginTime(now);
                        groupSendJobSon.setSendStartTime(now);
                    }else{//暂停中的任务延迟5分钟发送
                        groupSendJobSon.setBeginTime(now+60*5); //延迟5分钟
                        groupSendJobSon.setSendStartTime(now+60*5); //延迟5分钟
                    }

                    groupSendJobSon.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());

                    groupSendJobSon.setUpdateTime(now);

                    groupSendJobSon.setFinishCountSnapshot(groupSendJobSon.getFinishCount());

                    //从ES中获取该子任务的已发送数
//                    GroupSendJobIdFeignDto groupSendJobIdFeignDto = new GroupSendJobIdFeignDto();
//                    groupSendJobIdFeignDto.setId(groupSendJobSon.getId());
//                    UzaiRespVo<Integer> uzaiRespVo = uzaiBroadcastFeignService.groupSendFinishCount(groupSendJobIdFeignDto);
//                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
//                        if(Tools.getInteger(uzaiRespVo.getData()).intValue() != 0){
//                            groupSendJobSon.setFinishCountSnapshot(uzaiRespVo.getData());
//                        }
//                    }
                    groupSendJobMapper.updateByIdSelective(groupSendJobSon);
                }
            }
        }
    }

    /**
     * 暂停群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobIdDto
     * @return null
     */
    public void pauseGroupSendJob(GroupSendJobIdDto groupSendJobIdDto){
        if(groupSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobIdDto.getId(), groupSendJobIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能暂停");
        }

        Integer now = DateUtil.getNowTime();
        groupSendJob.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
        groupSendJob.setUpdateTime(now);
        groupSendJobMapper.updateById(groupSendJob);

        //批量修改子任务
        //查询未开始的子任务，修改状态为开始
        GroupSendJobQuery groupSendJobQuery = new GroupSendJobQuery();
        groupSendJobQuery.setMerId(groupSendJobIdDto.getMerId());
        groupSendJobQuery.setParentId(groupSendJob.getId());
        List<GroupSendJob> groupSendJobQueryList =  groupSendJobMapper.findByList(groupSendJobQuery);
        if(groupSendJobQueryList != null) {
            for (GroupSendJob groupSendJobSon : groupSendJobQueryList) {
                //进行中的任务-将状态修改成暂停
                if(groupSendJobSon.getStatus().intValue() == GroupSendStatusEnum.RUNNING.getValue().intValue()){
                    groupSendJobSon.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
                    groupSendJobSon.setUpdateTime(now);
                    groupSendJobMapper.updateByIdSelective(groupSendJobSon);
                }
            }
        }

    }

    /**
     * 结束群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobIdDto
     * @return null
     */
    public void finishGroupSendJob(GroupSendJobIdDto groupSendJobIdDto){
        if(groupSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobIdDto.getId(), groupSendJobIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能结束");
        }

        Integer now = DateUtil.getNowTime();
        groupSendJob.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
        groupSendJob.setUpdateTime(now);
        groupSendJobMapper.updateById(groupSendJob);

        //批量修改子任务
        GroupSendJobQuery groupSendJobQuery = new GroupSendJobQuery();
        groupSendJobQuery.setMerId(groupSendJobIdDto.getMerId());
        groupSendJobQuery.setParentId(groupSendJob.getId());
        List<GroupSendJob> groupSendJobQueryList =  groupSendJobMapper.findByList(groupSendJobQuery);
        if(groupSendJobQueryList != null) {
            for (GroupSendJob groupSendJobSon : groupSendJobQueryList) {
                groupSendJobSon.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
                groupSendJobSon.setUpdateTime(now);
                groupSendJobMapper.updateByIdSelective(groupSendJobSon);
            }
        }
    }

    /**
     * 删除群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobIdDto
     * @return null
     */
    public void deleteGroupSendJob(GroupSendJobIdDto groupSendJobIdDto){

//        if(true){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前版本不支持删除群发任务功能");
//        }

        if(groupSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobIdDto.getId(), groupSendJobIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()
                && groupSendJob.getStatus().intValue() != GroupSendStatusEnum.INIT.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只允许删除未开始和初始化的任务");
        }

        //删除主任务
        groupSendJobMapper.deleteById(groupSendJob.getId(), groupSendJobIdDto.getMerId());

        //删除子任务
        groupSendJobMapper.deleteByParentId(groupSendJob.getId(), groupSendJobIdDto.getMerId());

        //删除群发任务ES数据
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.setQuery(new TermQueryBuilder("parentJobId", groupSendJob.getId()));

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendJobIdDto.getMerId());
        elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_group_send_msg, deleteByQueryRequest);

    }

    /**
     * 修改个人微信通讯录群发任务
     * 条件：完成发送数不等于消息总数，且ES里已经没有消息了的子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobRepairDto
     * @return null
     */
    public void repairWxContactGroupSendJob(GroupSendJobRepairDto groupSendJobRepairDto){
        if(groupSendJobRepairDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id不能为空");
        }

        Merchant merchant = merchantMapper.selectById(groupSendJobRepairDto.getMerId());
        if(merchant == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendJobRepairDto.getMerId());


        //查找该运营商所有的个人微信通讯录子任务
        GroupSendJobQuery groupSendJobQuery = new GroupSendJobQuery();
        groupSendJobQuery.setMerId(groupSendJobRepairDto.getMerId());
        groupSendJobQuery.setSource(GroupSendJobSourceEnum.PRIVATE_CONTACTS.getId());
        //查询所有的个人通讯群发任务
        List<GroupSendJob> groupSendJobList  = groupSendJobMapper.findByList(groupSendJobQuery);
        if(groupSendJobList != null && groupSendJobList.size() > 0){
            for (GroupSendJob groupSendJob : groupSendJobList) {
                if(Tools.getLong(groupSendJob.getParentId()).longValue() != 0){ //子任务
                    if(groupSendJob.getSource().intValue() == GroupSendJobSourceEnum.PRIVATE_CONTACTS.getId()){//个人微信通讯录群发
                        if(Tools.getInteger(groupSendJob.getTotalCount()).intValue() != Tools.getInteger(groupSendJob.getFinishCount()).intValue()){ //发送总数和完成数不相等的子任务才修复
                            //查询发送消息列表已经没有的，才修复
                            //ES查询
                            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                            //运营商ID
                            boolQuery.must(QueryBuilders.termQuery("merId", groupSendJob.getMerId()));
                            //子任务id
                            boolQuery.must(QueryBuilders.termQuery("childJobId", groupSendJob.getId()));
                            searchSourceBuilder.query(boolQuery);
                            //排序
                            searchSourceBuilder.sort("createTime", SortOrder.DESC);
                            //查询消息总数
                            long msgNumber = elasticsearchUtilGroupMsg.searchTotal(uzai_group_send_msg, searchSourceBuilder);
                            //没有消息总数的子任务才处理
                            if(msgNumber == 0){
                                Long deviceUniqueId = groupSendJob.getDeviceUniqueId();
                                wxContactsService.repairBatchSendMessageTaskSync(groupSendJob);
                            }
                        }
                    }
                }
            }
        }

    }

}
